package com.lyy.common.utils.jxls;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @param beans 存放导出的数据
 * @param name 导出时用的名字
 * @param address 导出时用的模板
 *
 */
public class JxlsExport {
    public static boolean export(HttpServletRequest request, HttpServletResponse response, Map<String, Object> beans,String name,String address) {
        try {
            InputStream in = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //        模板路径
            URL url = new URL(address);
            HttpURLConnection conn = null;

                conn = (HttpURLConnection) url.openConnection();

            in = conn.getInputStream();

            //调用封装的工具类，传入模板路径，输出流，和装有数据的Map,按照模板导出
            JxlsUtils.exportExcel(in, baos, beans);

            // 设置请求返回类型
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(name.getBytes("gbk"), "ISO8859-1"));
            response.setContentLength(baos.size());
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
